/**
* @Author: 李晨光
* @Date: 2019/12/18
* @Version: 1.0
* @Last Modified by: 李晨光
* @Last Modified time: 2019/12/18
**/
<comment>
  # 积分兑换
</comment>
<template>
  <div id="Exchange" class="p-box">
    <div class="p-return">
      <mu-appbar color="primary" class="lan-header" style="box-shadow:none">
        <mu-button icon slot="left" v-close>
          <i class="iconfont angle-left iconangle-left"></i>
          <span class="lan-header-back">返回</span>
        </mu-button>积分兑换
        <mu-button icon slot="right" @click="scanCode" v-if="shop.id">
          <i class="iconfont iconsaoma"></i>
        </mu-button>
      </mu-appbar>
    </div>
    <div class="p-content">
      <div>
        <p class="select-project" v-if="showSelcetProject">
          <span class="project-name">{{org[0].label}}</span>
          <span class="project-change" @click="showOrgLog">切换项目</span>
        </p>
        <p class="select-shop">
          <label @click="showShopLog" class="shop-name">
            <span>{{shop.shopName}}</span>
            <i class="iconfont iconangle-down"></i>
          </label>
          <span class="shop-history" @click="goExchangeHis">兑换记录</span>
        </p>
        <!-- <mu-list>
          <mu-list-item
            style="text-align: center;align-items: center;display: flex;justify-content: center"
          >
            <div class="search">
              <mu-auto-complete
                :data="currentPeople?people:[]"
                max-height="120"
                :open-on-focus="false"
                v-model="currentPeople"
                placeholder="请输入姓名/工号"
                class="search-input"
                @select="selectPeople"
              >
                <template slot-scope="scope">
                  <mu-list-item-content v-html="scope.highlight"></mu-list-item-content>
                </template>
              </mu-auto-complete>
            </div>
          </mu-list-item>
        </mu-list>-->
        <div class="dim-search">
          <input
            type="text"
            v-model="currentPeople"
            ref="searchInput"
            class="search-input"
            placeholder="请输入姓名/工号"
            @input="search"
          />
          <div class="searchList-container" v-if="currentPeople&&people.length">
            <ul class="search-list">
              <li
                v-for="(item,index) in people"
                :key="'user'+index"
                @click="selectPeople(item)"
                :class="item.item.userId==nowUserId?'active':''"
              >
                <span>{{item.value}}</span>
              </li>
            </ul>
          </div>
        </div>
      </div>

      <div class="person-container" v-if="selectResult.userId">
        <div class="person-list">
          <table class="custom-table">
            <tr>
              <td>姓名</td>
              <td>{{selectResult.userName}}</td>
            </tr>
            <tr>
              <td>工号</td>
              <td>{{selectResult.employeeNum}}</td>
            </tr>
            <tr>
              <td>项目</td>
              <td>{{selectResult.orgName}}</td>
            </tr>
            <tr>
              <td>单位</td>
              <td>{{selectResult.unitName}}</td>
            </tr>
            <tr>
              <td colspan="2">当前可兑换积分：{{selectResult.leftScore}}</td>
            </tr>
          </table>
        </div>
        <div class="person-form" v-if="selectResult.leftScore>0">
          <div class="person-label">输入兑换积分</div>
          <div class="person-click">
            <input type="number" v-model="total" class="exchange-input" />
            <span @click="exchange" class="exchange-btn">确认兑换</span>
          </div>
        </div>
        <!-- <div class="person-history">
          <span @click="goExchangeHis">查询历史兑换记录</span>
        </div>-->
      </div>
      <NoData v-else />
    </div>
    <Org
      ref="org"
      v-model="org"
      @change="orgChange"
      :open="openOrg"
      title="选择项目"
      orgType="currOrgProject"
      @close="closeOrgDialog"
      @confirm="confirmOrgDialog"
    ></Org>
    <Shop ref="Shop" v-model="shop" @change="shopChange" :lists="lists" @close="closeShopDialog"></Shop>
  </div>
</template>

<script>
import { MessageBox } from "mint-ui";
import Org from "@/select/org/Org.vue";
import Shop from "@/select/shop/Shop.vue";
import Search from "@/search/Search.vue";
import debounce from "lodash.debounce";
export default {
  name: "Exchange",
  components: {
    Org,
    Search,
    Shop
  },
  props: {},
  data() {
    return {
      api: {
        getUserMsgApi: "/safety/starObserve/userInfo" // 获取人员信息
      },
      showSelcetProject: false,
      openOrg: false,
      openShop: false,
      nameOrEmpNo: "",
      total: null,
      lists: [],
      shop: {
        id: "",
        shopName: ""
      },
      org: [
        {
          label: "",
          value: "",
          disabled: false,
          checked: false,
          hasChecked: true,
          hasChildren: true
        }
      ],
      userList: [],
      people: [],
      currentPeople: "",
      selectResult: {
        userId: ""
      },
      nowUserId: ""
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (from.name == "Navs") {
        vm.initPage();
      }
    });
  },
  computed: {},
  created() {},
  mounted() {},
  watch: {
    currentPeople: {
      handler(val) {
        if (!val) {
          this.people = [];
        }
      },
      deep: true
    }
  },
  methods: {
    initPage() {
      if (this.$A.GS("orgInfo")["type"] == 1) {
        this.openOrg = false;
        this.showSelcetProject = false;
        this.org[0].label = this.$A.GS("orgInfo")["orgName"];
        this.org[0].value = this.$A.GS("orgInfo")["orgId"];
        this.getShopList();
      } else {
        this.openOrg = true;
        this.showSelcetProject = true;
      }
    },
    getShopList() {
      this.$openLoading();
      let params = {
        orgId: this.org[0].value,
        type: 1,
        current: -1,
        size: 10
      };
      this.$A.Go("get", "/safety/shop/pageList", params).then(res => {
        this.$closeLoading();
        if (res.code == 200 && res.body.rows && res.body.rows.length) {
          let lists = [];
          res.body.rows.forEach(item => {
            if (item.status == 0) {
              lists.push(item);
            }
          });
          this.lists = lists;
          this.shop = this.lists[0];
        } else {
          this.lists = [];
        }
      });
    },
    selectPeople(data) {
      this.currentPeople = data.value;
      this.selectResult = data.item;
      this.nowUserId = data.item.userId;
      this.people = [];
    },
    changePeople(value) {},
    goExchangeHis() {
      this.$router.push({
        name: "ExchangeRecords",
        query: {
          shopId: this.shop.id,
          orgId: this.org[0].value
        }
      });
    },
    search: debounce(function(val) {
      this.getUserMsg();
    }, 1000),
    getUserMsg() {
      if (!this.currentPeople) {
        return;
      }
      let params = {
        nameOrEmpNo: this.currentPeople,
        orgId: this.org[0].value, //102,
        userId: "",
        type: 0
      };
      this.$A
        .Go("get", this.api.getUserMsgApi, params)
        .then(response => {
          Util.processRes(response, () => {
            if (response.body.length) {
              let list = [];
              response.body.forEach(item => {
                list.push({
                  value: item.userName + " " + item.employeeNum,
                  item: item
                });
              });
              this.people = list;
            } else {
              this.people = [];
            }
          });
          Util.processError(this, response);
        })
        .catch(err => {
          this.$closeLoading();
          console.log(err);
        });
    },
    orgChange(ev) {
      this.getShopList();
      this.getUserMsg();
    },
    shopChange(data) {
      this.shop = data;
    },

    showOrgLog() {
      this.openOrg = true;
    },
    showShopLog() {
      this.$nextTick(() => {
        this.$refs["Shop"].init();
      });
    },
    confirmOrgDialog() {
      this.openOrg = false;
    },
    closeOrgDialog() {
      this.$router.go(-1);
      this.openOrg = false;
    },
    closeShopDialog() {
      this.$refs["shop"].close();
    },
    exchange() {
      if (
        Number(this.total) > 0 &&
        Number(this.total) <= Number(this.selectResult.leftScore)
      ) {
        this.$nextTick(() => {
          MessageBox({
            message: `确认为${this.selectResult.userName}(工号${this.selectResult.employeeNum})兑换${this.total}积分？`,
            showCancelButton: true,
            showConfirmButton: true,
            confirmButtonText: "确认",
            cancelButtonText: "取消"
          })
            .then((value, action) => {
              if (value == "confirm") {
                this.$A
                  .Go("post", "/safety/shop/exchange", {
                    exchangeScore: this.total, //兑换分数
                    shopId: this.shop.id, //商铺id
                    userId: this.selectResult.userId
                  })
                  .then(res => {
                    this.$closeLoading();
                    if (res.code == 200) {
                      this.getUserMsg();
                      this.selectResult.leftScore =
                        this.selectResult.leftScore - this.total;
                      this.$router.push({
                        name: "ExchangeResult",
                        query: {
                          type: "success"
                        }
                      });
                    } else {
                      this.$router.push({
                        name: "ExchangeResult",
                        query: {
                          type: "error"
                        }
                      });
                    }
                  });
              } else {
              }
            })
            .catch(err => {});
        });
      } else {
        this.$A.MS(`请输入正确的积分`);
      }
    },
    scanCode() {
      wx.ready(() => {
        wx.checkJsApi({
          jsApiList: ["invoke", "scanQRCode"], // 需要检测的JS接口列表，所有JS接口列表见附录2,
          success: res => {
            // 以键值对的形式返回，可用的api值true，不可用为false
            // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
          }
        });
        wx.invoke("enterpriseVerify", {}, res => {
          // alert(JSON.stringify(res));
        });
        wx.scanQRCode({
          desc: "scanQRCode desc",
          needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
          scanType: ["qrCode"], // 可以指定扫二维码还是条形码（一维码），默认二者都有
          success: res => {
            this.$openLoading();
            let data = JSON.parse(res.resultStr);
            // this.
            let params = {
              obj: {
                orgId: this.org[0].value, // 组织ID
                roleId: "",
                employeeNumber: data.userNumber, // 工号
                userName: ""
              },
              pageNo: 1,
              pageSize: 2
            };
            this.$A.Go("post", "/safety/org", params).then(response => {
              this.$closeLoading();
              console.log(response);
              if (
                response.code == 200 &&
                response.body &&
                response.body.length
              ) {
                this.$router.push({
                  name: "ExchangeSao",
                  query: {
                    shopId: this.shop.id,
                    leftScore: data.leftScore, //200,
                    orgId: data.projecId, //"60820458500522390",
                    orgName: data.projecName,
                    type: data.type, //"1",
                    unitId: data.unitId, //null,
                    unitName: data.unitName, // null,
                    userId: data.userId, //"155723",
                    userName: data.userName, //"王腾飞",
                    employeeNum: data.userNumber, // "500A2925",
                    userType: data.userType //"1"
                  }
                });
              } else {
                this.$A.MS("无人员信息");
              }
            });
          },
          error: res => {
            if (res.errMsg.indexOf("function_not_exist") > 0) {
              alert("版本过低请升级");
            }
          }
        });
      });
    }
  },
  destroyed() {}
};
</script>

<style lang="scss">
#Exchange {
  .search-input {
    margin-bottom: 0 !important;
    width: 100%;
    .mu-input-line,
    .mu-input-focus-line {
      display: none;
    }
    input {
      width: 3.47rem;
      height: 0.33rem;
      background: rgba(235, 235, 237, 1);
      border-radius: 0.83rem;
      padding: 0 0.15rem;
      font-size: 0.13rem;
      font-weight: 400;
      color: rgba(61, 61, 61, 1);
      text-align: center;
    }
  }
  .lan-nodata {
    flex: 1;
  }
  .search {
    width: 3.47rem;
    height: 0.33rem;
    /*background: rgba(248, 248, 248, 1);*/
    border-radius: 0.83rem;
    font-size: 0.13rem;
    font-weight: 400;
    color: rgba(140, 140, 140, 1);
    text-align: center;
    align-items: center;
    display: flex;
    justify-content: center;
  }
  .p-content {
    background: #fff;
    padding: 0.14rem;
    .select-project {
      display: flex;
      height: 0.4rem;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 0.08rem;
      .project-name {
        font-size: 0.2rem;
        flex: 1;
        margin-right: 0.25rem;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-weight: 500;
        color: rgba(61, 61, 61, 1);
      }
      .project-change {
        font-size: 0.15rem;
        font-weight: 500;
        color: rgba(0, 128, 203, 1);
      }
    }
    .select-shop {
      font-weight: 500;
      display: flex;
      height: 0.33rem;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 0.15rem;
      .shop-name {
        flex: 1;
        font-size: 0.17rem;
        color: rgba(61, 61, 61, 1);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .shop-history {
        font-size: 0.14rem;
        font-weight: 500;
        color: rgba(0, 128, 203, 1);
      }
    }
    .person-container {
      margin-top: 0.35rem;
      padding: 0 0.23rem;
      .custom-table {
        tr:not(:last-child) {
          td:first-child {
            width: 0.8rem;
            background: rgba(245, 245, 245, 1);
          }
          td:last-child {
            text-align: right;
          }
        }
        tr {
          td {
            padding: 0.11rem;
          }
        }
        tr:last-child {
          td {
            padding: 0.15rem;
          }
        }
      }
      .person-form {
        margin-top: 0.15rem;
        .person-label {
          font-size: 0.15rem;
          font-weight: 500;
          color: rgba(61, 61, 61, 1);
          font-weight: bold;
        }
        .person-click {
          display: flex;

          .exchange-input {
            flex: 1;
            background-color: #fff;
            background-image: none;
            border: 1px solid #ccc;
            border-radius: 4px;
            height: 0.4rem;
            padding: 0 0.14rem;
            -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
            box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
          }
          .exchange-btn {
            margin-left: 0.05rem;
            display: inline-block;
            width: 1.03rem;
            height: 0.4rem;
            line-height: 0.4rem;
            text-align: center;
            background: rgba(0, 128, 203, 1);
            border-radius: 0.04rem;
            color: #fff;
          }
        }
      }
      .person-history {
        margin-top: 0.44rem;
        font-size: 0.13rem;
        color: rgba(0, 128, 203, 1);
        text-align: center;
      }
    }
  }
}
</style>
